import { Toast } from "antd-mobile"
import {reqlogin} from "../../request/api"

//状态
const initState ={
    user:{
        phone: "",
        password: "",
    },
    userInfo:localStorage.getItem("isLogin")?JSON.parse(localStorage.getItem("isLogin")):{}
}

//actionType
const TYPES={
    LOGIN_CHANGE_USER:"LOGIN_CHANGE_USER",
    LOGIN_CHANGE_USERINFO:"LOGIN_CHANGE_USERINFO"
}

//修改state reducer
const reducer = (state=initState,action)=>{
    switch(action.type){
        case TYPES.LOGIN_CHANGE_USER:
            return{
                ...state,
                user:{
                    ...state.user,
                    [action.key]:action.value
                }
            }
        case TYPES.LOGIN_CHANGE_USERINFO:
            return{
                ...state,
                userInfo:action.userInfo
            }
        default:
            return state;
    }
}

//逻辑和异步actions actionCreators
export const actions={
    changeUser:(key,value)=>({type:TYPES.LOGIN_CHANGE_USER,key,value}),
    changeUserInfo:(userInfo)=>{
        if(userInfo.token){
            localStorage.setItem("isLogin",JSON.stringify(userInfo))
        }else{
            localStorage.removeItem("isLogin")
        }
        return {type:TYPES.LOGIN_CHANGE_USERINFO}
    },
    doLogin:(push)=>{
        return (dispatch,getState)=>{
            let user= getUser(getState())

            reqlogin(user).then(d=>{
                if(d.data.code===200){
                    Toast.show({
                        content:d.data.msg
                    })
                    dispatch(actions.changeUserInfo(d.data.list))
                    push("/index/home")
                }else{
                    Toast.show({
                        content:d.data.msg
                    })
                }
            })
        }
    }
}

//导出数据 Selectors
export const getUser = state => state.login.user;
export const getUserInfo=state=>state.login.userInfo;
//导出reduer
export default reducer;